package com.zjb.home.boxingtu.view.other;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.zjb.home.boxingtu.R;


/**
 * Created by zhangjiebo on 2019/10/24.
 *  线条指示器
 * @author ZhangJieBo
 */
public class LineIndicatorView extends View {

    private Paint paint;
    private int num = 3;
    private float offset;
    private int position = 0;

    public LineIndicatorView(Context context) {
        super(context);
        init();
    }

    public LineIndicatorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LineIndicatorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(ContextCompat.getColor(getContext(), R.color.basic_color));
        paint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setStrokeWidth(getHeight());
        float oneLineWidth = (getWidth() - getHeight()) / (float) num;
        canvas.drawLine(oneLineWidth*position+getHeight()/2f+offset,getHeight()/2f,oneLineWidth*(position+1f)+getHeight()/2f+offset,getHeight()/2f,paint);
    }

    public void bindViewPager(ViewPager viewPager){
        num = viewPager.getAdapter().getCount();
        invalidate();
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                LineIndicatorView.this.position =position;
                offset = (getWidth() - getHeight()) / (float) num * positionOffset;
                invalidate();
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
}
